var querystring = require('querystring');
var config = {
    "path":"/",
    "domain":null,
    "httpOnly":false,
    "secure":false,
    "expires":0
};

exports.config = config;

exports.create = function(req, res){
    return new cookie(req, res);
}

var cookie = function (req, res) {
    var self  = this;
    var data;
    var $cookie = [];
    var $nowTime = new Date().getTime();
    // Serialize the given object into a cookie string.
    var serializeCookie = function (key, val) {
        var pairs = [];
        if (val === null || val === false) {
            pairs.push(key + "=''");
            var expires = (config.expires + 86400) * -1;
        }
        else {
            pairs.push(key + '=' + encodeURIComponent(val));
            var expires = parseInt(config.expires);
        }

        if (config.domain) pairs.push('domain=' + config.domain);
        if (config.path) pairs.push('path=' + config.path);
        if (expires) {
            var time = $nowTime + expires * 1000;
            var date = new Date(time);
            var expiresDate = date.toGMTString();
            pairs.push('expires=' + expiresDate);
        }
        if (config.httpOnly) pairs.push('httpOnly');
        if (config.secure) pairs.push('secure');
        return pairs.join('; ');
    };
    //parse Cookie
    var parseCookie = function () {
        if (!req.headers.cookie) {
            return false;
        }
        cache = querystring.parse(req.headers.cookie,';','=');
    };

    this.login = function (key,info, callback) {
        return this.set(info, callback);
    }

    this.get = function (keys, callback) {
        if(typeof callback!='function'){
            callback = $.callback;
        }
        var val = $.dataSelect(data, keys);
        return callback(null,val);
    }

    this.set = function (key, val, callback) {
        if(typeof val == 'function'){
            callback = val;
            val = null;
        }
        else if(typeof callback!='function'){
            callback = $.callback;
        }
        if(typeof key=='object'){
            for (var k in key) {
                $cookie.push(serializeCookie(k, key[k]));
            }
        }
        else{
            $cookie.push(serializeCookie(key, val));
        }
        res.setHeader("Set-Cookie", $cookie);
        return callback(null,true);
    }

    this.del = function (key,callback) {
        if(typeof callback!='function'){
            callback = $.callback;
        }
        $cookie.push(serializeCookie(key,null));
        res.setHeader("Set-Cookie", $cookie);
        return callback(null,true);
    }

    parseCookie();

}